<template>
  <div style="display: flex; align-items: center; flex-wrap: wrap;">
    <input v-model="node1" placeholder="Enter node1 ID" style="margin-right: 8px;" />
    <input v-model="node2" placeholder="Enter node2 ID" style="margin-right: 8px;" />
    <button @click="predictLink" style="margin-right: 8px;">Predict Link</button>
    <button @click="repredictLinks">Repredict Link</button>
    <p v-if="linkProbability !== null">
      Predicted Probability: {{ linkProbability }}
    </p>
    <p v-if="errorMessage">{{ errorMessage }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { mapMutations, useStore } from 'vuex'; // 使用 useStore 来访问 Vuex store
import { eventBus } from '../eventBus'; // 引入事件总线

// 定义响应式变量
const node1 = ref('');
const node2 = ref('');
const linkProbability = ref(null);
const errorMessage = ref('');

// 初始化 Vuex store
const store = useStore();

onMounted(async () => {
  await nextTick(); // 确保 DOM 更新完成
  // 监听节点选择事件
  eventBus.on('node-ids', ({ id1, id2 }) => {
    console.log('Node IDs selected:', id1, id2); // 添加日志以确认事件触发 
    node1.value = id1; // 更新响应式变量
    node2.value = id2; // 更新响应式变量
  });
});

// 定义预测链接的方法
const predictLink = async () => {
  try {
    const response = await axios.post('http://localhost:5000/predict', {
      node1: node1.value,
      node2: node2.value,
    });
    linkProbability.value = response.data.link_probability;
    // 更新 Vuex store 中的 dataResult
    store.commit('SET_DATA_RESULT', response.data.data_result);
    errorMessage.value = ''; // 清除错误信息
  } catch (error) {
    console.error('There was an error fetching the prediction!', error);
    errorMessage.value = 'Failed to fetch prediction. Please check your input.';
  }
};

// 定义重新预测链接的方法
const repredictLinks = async () => {
  try {
    const response = await axios.post('http://localhost:5000/repredict-links', {
      node1: node1.value,
      node2: node2.value,
    });
    linkProbability.value = response.data.link_probability;
    // 更新 Vuex store 中的 dataResult
    store.commit('SET_DATA_RESULT', response.data.data_result);
    errorMessage.value = ''; // 清除错误信息
  } catch (error) {
    console.error('There was an error repredicting the links!', error);
    errorMessage.value = 'Failed to repredict links. Please check your input.';
  }
};
</script>

<style scoped>
/* 添加一些样式 */
input, button {
  display: block;
  margin: 10px 0;
}
</style>